//
//  PlayerVC.m
//  One
//
//  Created by mac on 16/6/2.
//  Copyright © 2016年 mac. All rights reserved.
//

#import "PlayerVC.h"
#import <AVFoundation/AVFoundation.h>

//typeof (void ^(completedPlayingBlock)();

@interface PlayerVC ()
{
    BOOL inOperation;
    AVPlayer *player;
    AVPlayerItem *playerItem;
    UITapGestureRecognizer *tap;
    AVPlayerLayer *layer;
    float totalMovieDuration;
    NSTimer *timer;
    float currentTime;
    
}
@end

@implementation PlayerVC

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
//    [self layoutPlayer];
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    [self layoutPlayer];
}

- (void)layoutPlayer
{
    inOperation = YES;
    self.deepView.backgroundColor = [UIColor colorWithRed:56/255.0 green:59/255.0 blue:61/255.0 alpha:0.3];
    self.topView.backgroundColor = [UIColor clearColor];
    self.deepView.tag = 10086;
    self.topView.tag = 10000;
    tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapAction)];
    [self.bgView addGestureRecognizer:tap];
    
    [self.mySlider setThumbImage:[UIImage imageNamed:@"kr-video-player-point_10x10_.png"] forState:UIControlStateNormal];
    [self.mySlider addTarget:self action:@selector(SliderAction) forControlEvents:UIControlEventValueChanged];
    
    
    if (!player) {
        NSLog(@"url---%@",self.urlStr);
        NSURL *url = [NSURL URLWithString:[NSString stringWithFormat:@"%@",self.urlStr]];
        playerItem = [AVPlayerItem playerItemWithURL:url];
        //playerItem status
        NSLog(@"status-----item:%d----player:%d",(int)playerItem.status,(int)player.status);
        [playerItem addObserver:self forKeyPath:@"status" options:NSKeyValueObservingOptionNew context:nil];
        
        [playerItem addObserver:self forKeyPath:@"loadedTimeRanges" options:NSKeyValueObservingOptionNew context:nil];
        CGFloat time =        playerItem.duration.value;
        
        NSLog(@"---%.2f",time);
        
        
        player = [AVPlayer playerWithPlayerItem:playerItem];
        [[NSNotificationCenter defaultCenter]  addObserver:self selector:@selector(playbackFinished:) name:AVPlayerItemDidPlayToEndTimeNotification object:nil];
                                                                                   
        
        layer = [AVPlayerLayer playerLayerWithPlayer:player];
        
        layer.videoGravity = AVLayerVideoGravityResizeAspectFill;
        layer.frame = self.view.bounds;
//        [self.bgView.layer addSublayer:layer];
        [self.bgView.layer insertSublayer:layer atIndex:0];
        
        
        [layer.player play];
        
        NSLog(@"-ssss------%f",CMTimeGetSeconds(playerItem.duration));
        
        //add progress Observer
        [self addProgressObserver];
        
    }
}

- (void)addProgressObserver
{
    AVPlayerItem *currentItem = player.currentItem;
    __weak typeof (self)weakSelf = self;
    //set once second
    [player addPeriodicTimeObserverForInterval:CMTimeMake(1.0, 1.0) queue:dispatch_get_main_queue() usingBlock:^(CMTime time) {
        float current =  CMTimeGetSeconds([playerItem duration]);
        weakSelf.timeLabel.text = [weakSelf transTimeWithTime:current];
        if (current) {
            weakSelf.mySlider.value = current/totalMovieDuration;
            if (weakSelf.mySlider.value == 1) {
                weakSelf.stopButton.selected = NO;
                CMTime currentCMTime = CMTimeMake(0, 1);
                [player seekToTime:currentCMTime completionHandler:^(BOOL finished) {
                    weakSelf.mySlider.value = 0.0f;
                }];
            }
        }
    }];
    
}

- (void)playbackFinished:(NSNotification *)noti
{
    [timer invalidate];
    timer = nil;
    [self.view removeFromSuperview];
}

- (void)tapAction
{
    static int count = 0;
    count ++;
    UIView *hideView = (UIView *) [self.bgView viewWithTag:10086];
    UIView *hide2 = (UIView *)[self.bgView viewWithTag:10000];
    if (count%2 == 0) {
        
        hide2.alpha = 0;
        hideView.alpha = 0;
    }else
    {
        hide2.alpha = 1;
        hideView.alpha = 1;
    }
}

#pragma mark--Slider
- (void)SliderAction
{
    NSLog(@"slider");
    inOperation = NO;
    CMTime currentCMTime = CMTimeMake(self.mySlider.value *totalMovieDuration, 1);
    [player seekToTime:currentCMTime completionHandler:^(BOOL finished) {
        [player play];
        self.stopButton.selected = YES;
    }];
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark--KVO
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSString *,id> *)change context:(void *)context
{
    NSLog(@"KVO");
    //AVPlayerItem *item = object;
    if ([keyPath isEqualToString:@"status"]) {
        AVPlayerStatus status = [[change objectForKey:@"new"] intValue];
        if (status == AVPlayerStatusReadyToPlay) {
            
            CGFloat time = playerItem.duration.value;
            
            NSLog(@"---%.2f",time);
            
            CMTime tim2 =  playerItem.duration;
            NSLog(@"正在播放--%.2f",CMTimeGetSeconds(tim2));
            CMTime totalTime = playerItem.duration;
            totalMovieDuration  = (CGFloat)totalTime.value/totalTime.timescale;
            self.mySlider.maximumValue = totalMovieDuration + 1;
            
            self.stopButton.selected = YES;
            
            if (!timer) {
                timer = [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(onTimer) userInfo:nil repeats:YES];
                [[NSRunLoop mainRunLoop]  addTimer:timer forMode:NSRunLoopCommonModes];
                [timer fire];
            }
            
            NSString *showTimeNow = [self transTimeWithTime:totalMovieDuration];
            self.timeLabel.text = showTimeNow;
        }
    }else if ([keyPath isEqualToString:@"loadedTimeRanges"]){
        NSArray *array = playerItem.loadedTimeRanges;
        NSLog(@"array----%@",array);
        //缓冲范围
        CMTimeRange timeRange = [array.firstObject CMTimeRangeValue];
        float startSeconds = CMTimeGetSeconds(timeRange.start);
        float durationSeconds = CMTimeGetSeconds(timeRange.duration);
        
        //totalRange
        NSTimeInterval totalBuffer = startSeconds + durationSeconds;
        NSLog(@"totalBuffer----%.2f",totalBuffer);
        
        //refresh slider
        self.mySlider.minimumValue = totalBuffer * 1.0 /totalMovieDuration;
        
    }
}

- (NSString *)transTimeWithTime:(CGFloat)time
{
    NSDate *d = [NSDate dateWithTimeIntervalSince1970:totalMovieDuration];
    NSDateFormatter *formate = [[NSDateFormatter alloc] init];
    if (totalMovieDuration/3600 >= 1) {
        [formate setDateFormat:@"HH:mm:ss"];
    }else
    {
        [formate setDateFormat:@"mm:ss"];
    }
    NSString *showTimeNow = [formate stringFromDate:d];
    return showTimeNow;
}

- (void)onTimer
{
    currentTime = totalMovieDuration - 1;
    NSString *nowtime = [self transTimeWithTime:currentTime];
    NSString *totalTime = [self transTimeWithTime:totalMovieDuration];
    self.timeLabel.text = [NSString stringWithFormat:@"%@/%@",nowtime,totalTime];
    
}
/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

- (IBAction)stopButton:(id)sender {
    self.stopButton.selected = !self.stopButton.selected;
    if (self.stopButton.selected == YES) {
        [player pause];
        [timer setFireDate:[NSDate distantFuture]];
        
    }else{
//        [player]
        [timer setFireDate:[NSDate date]];
    }
}

- (IBAction)fullScreenClick:(id)sender {
    NSNumber *value = [NSNumber numberWithInt:UIInterfaceOrientationLandscapeRight];
    [[UIDevice currentDevice]  setValue:value forKey:@"orientation"];
    
}
- (IBAction)removeViewBtn:(id)sender {
    [self.view removeFromSuperview];
    [timer invalidate];
    timer = nil;
}

- (void)dealloc
{
    [playerItem removeObserver:self forKeyPath:@"status"];
    [playerItem removeObserver:self forKeyPath:@"loadedTimeRanges"];
}



@end
